package com.demo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class PattenUtil {
	
	private static final PattenUtil INSTANCE = new PattenUtil();
	
	public static PattenUtil getInstance(){
		return INSTANCE;
	}
	
	public static final String ALIAS = "[\\w_\u4E00-\u9FA5]+";
	
	public static String match(String regex, String str){
		if (StringUtils.isBlank(str)) return null;
		
		StringBuffer temp = new StringBuffer();
		// 正则初始化
		Pattern p = Pattern.compile(regex);
		// 匹配器初始化
		Matcher m = p.matcher(str);
		// 匹配查询
		while (m.find()) {
			temp.append(m.group());
		}
		return temp.toString();
	}
	
	public static String matchAlias(String id){
		return match(ALIAS, id);
	}
	
	public static boolean matches(String pattern, String source) {
		if (pattern == null || source == null) {
			return false;
		}
		pattern = pattern.trim();
		source = source.trim();
		if (pattern.endsWith("*")) {
			int length = pattern.length() - 1;
			if (source.length() >= length) {
				if (pattern.substring(0, length).equals(
						source.substring(0, length))) {
					return true;
				}
			}
		} else if (pattern.startsWith("*")) {
			int length = pattern.length() - 1;
			if (source.length() >= length
					&& source.endsWith(pattern.substring(1))) {
				return true;
			}
		} else if (pattern.contains("*")) {
			int start = pattern.indexOf("*");
			int end = pattern.lastIndexOf("*");
			if (source.startsWith(pattern.substring(0, start))
					&& source.endsWith(pattern.substring(end + 1))) {
				return true;
			}
		} else {
			if (pattern.equals(source)) {
				return true;
			}
		}
		return false;
	}
	
	public static String  formatOutPage(String out,HttpServletRequest req){
		Cookie[] cookies = req.getCookies();
		Cookie c = null;
		
		List<String> ls = new ArrayList<>();
		String p = "(?<=\\{)(.+?)(?=\\})";
		String str = "/manager/{sys}";
		Pattern pattern = Pattern.compile(p);
		Matcher matcher = pattern.matcher(str);
        while(matcher.find())
        	ls.add(matcher.group());
        for (String s : ls) {
        	for (int i = 0; cookies!=null && i < cookies.length; i++){
    			c = cookies[i];
    			if (c.getName().equals(s)){
    				out = out.replace("{"+s+"}", c.getValue());
    				break;
    			}
    		}
		}
		return out;
	}
}
